package com.huang.consumer_mall.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huang.consumer_mall.util.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String,Object> map =new HashMap<>();
        //获取请求头中的token
        String token = request.getHeader("token");

        try{
            JwtUtils.verify(token);  //验证token
        //System.out.println("验证成功！！！");
            return true;
        } catch (SignatureVerificationException e){
            e.printStackTrace();
            map.put("msg","签名无效");
        } catch (TokenExpiredException e){
            e.printStackTrace();
            map.put("msg","token已过期");
        } catch (AlgorithmMismatchException e){
            e.printStackTrace();
            map.put("msg","token算法不匹配");
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg","token无效");
        }
        map.put("status",false);
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        return false;
    }
}
